<template><!-- 联系计划 -->
  <div class="plan" v-loading="loading" v-if="reload==='history'&&!loading">
    <div class="zhezhao" :class="listent || edit?'show-zhezhao':'hide-zhezhao'" v-if="callScreen"></div>
    <el-row class="p-filter" >
      <el-col :span="14" class="til">
        <span class="clock">
          <i class="iconfont icon-zongshichang"></i>
        </span>
        {{$t('public.historyNum', {count: count})}}
      </el-col>
      <el-col :span="10" class="right">
        <el-dropdown @command="handleCommandTime" size="small">
          <span class="el-dropdown-link">
            {{$t('public.time')}}: <span>{{filterTimeName}}</span><i class="el-icon-arrow-down el-icon--right"  m7automation="time_dropDownBox"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="item in time" :command="item.type">{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        &nbsp;&nbsp;&nbsp;
        <el-dropdown @command="handleCommandType" size="small">
          <span class="el-dropdown-link">
          {{$t('public.type')}}: <span>{{filterTypeName}}</span><i class="el-icon-arrow-down el-icon--right" m7automation="type_dropDownBox"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="item in businessType" :command="item.type">{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-row v-if="!loading">
      <!-- 录音和备注弹窗开始 -->
      <el-dialog modal-append-to-body lock-scroll append-to-body :title="$t('call.listenAudio')" :visible.sync="listent" :width="callScreen?'70%':'50%'" :modal="callScreen?false:true" @close="closeModal" @open="openModal">
        <old-audio-common v-if="showOld" flagId="contact_history_old" :srcUrl="recordFile" :refreshAudio="refreshAudio" :isShowAudioDownload="false" :isShowSubmitAudio="false"  :currentObj="{}" :pauseAudio="pauseAudio"></old-audio-common>
        <audio-common v-if="!showOld" flagId="contact_history" @showOldAudio="showOldAudio" :callStatus="callStatus" :srcUrl="recordFile" :refreshAudio="refreshAudio" :isShowAudioDownload="false" :isShowSubmitAudio="false"  :currentObj="{}" :pauseAudio="pauseAudio"></audio-common>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll append-to-body :title="$t('public.editComments')" :visible.sync="edit" :width="callScreen?'70%':'30%'" :modal="callScreen?false:true">
        <el-input size="mini" type="textarea" v-model="comments" :style="callScreen?'padding:30px;width:90%':''"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="edit = false" class='primary_btn'>{{$t('public.cancel')}}</el-button>
          <el-button type="primary" @click="submitEdit" class='primary_btn'>{{$t('public.confirm')}}</el-button>
        </span>
      </el-dialog>
      <el-dialog :close-on-click-modal="true" modal-append-to-body lock-scroll append-to-body :width="callScreen?'70%':'800px'"  :title="contactHistoryInfo.title" id="contactHistory-dialog" :class="[contactHistoryInfo._id && contactHistoryInfo.labelValue === 2 ? 'email_dialog' : '', callScreen?'call-screen':'']" class="bussiness-dialog-padding" :modal="callScreen?false:true" :visible.sync="contactHistoryInfo.isdealog" @close="off" @open="open">
        <div :element-loading-text="$t('public.loadingText')"  v-loading="!contactHistoryInfo._id">
           <Bussiness :busId="contactHistoryInfo._id"
                   :showHistory="true"
                   v-if="contactHistoryInfo._id && contactHistoryInfo.labelValue === 1"
                   @event="businessEvent"
                   :callScreen="true"
                   class="business-dialog">
        </Bussiness>
        <emailDetails
          :id="contactHistoryInfo._id"
          :lastEmail="lastEmail"
          :style="callScreen?'height:390px;padding:0 20px':''"
          v-if="contactHistoryInfo._id && contactHistoryInfo.labelValue === 2">
        </emailDetails>
        <webChatView
          :showFlag = "true"
          :chatInformationId ="contactHistoryInfo._id"
          v-if="contactHistoryInfo._id && contactHistoryInfo.labelValue === 3">
        </webChatView>
          <DetailTable
            audioId="callHistoryAudio"
            :callData="callData"
            :style="callScreen?'min-height:610px':''"
            :pauseAudio="pauseAudio"
            v-if="contactHistoryInfo._id && contactHistoryInfo.labelValue === 4">
          </DetailTable>
        </div>
      </el-dialog>
      <!-- 录音和备注弹窗结束 -->
      <el-col :span="24" class="line">
        <ul class="border">
        <template v-for="(con, index) in cons" >
          <li v-if="con.detail==1" class="treat el-col">
            <span class="" :class="con.sclass">
              <div class="timer">{{con.createTime}}</div>
              <span :class="con.type" class="ico">
                <strong v-if="con.type === 'icon-wxmini'" class="iconfont icon-weixinzixun"></strong>
                <strong v-if="con.type === 'icon-remoteassist'" class="iconfont icon-yuanchengkongzhi"></strong>
                <strong v-else class="iconfont" :class="con.type"></strong>
              </span>
            </span>
              <p class="el-col-24 aa" v-if="con.type ==='icon-remoteassist'">
                {{$t('remoteControl.remoteControl')}} {{$t('remoteControl.connectTime', {time: con.connectTime})}}
              </p>
              <p class="el-col-24 aa" v-if="con.callType=='callin' || con.callType=='callout'">
                <call-status :status="con.status"></call-status>
                <template v-if="con.recordFile && isListent">
                <span class="time" @click.stop="popup(con.recordFile, con.status)">
                  <span class="play">
                    <strong class="pla"></strong>
                  </span>
                   <!--{{con.callTimeLen}}-->
                </span>
                  <!-- <span :class="con.ico">
                    <strong class="iconfont icon-biaoqing"></strong>
                  </span> -->
                </template>
              </p>
              <p class="el-col-24" v-else>{{con.status}}</p>
              <h3 class="el-col-10" :class="callScreen?'call-h3':''">
                {{con.sort}}&nbsp;&nbsp;
                <span :class="[con.type==='icon-gongdan'?'color-green':'']" v-if="con.type ==='icon-gongdan'" @click.stop="isDealog('showBussinessDetails',con._id,'')">{{con.businessTypeName}}</span>
                <span :class="[con.type==='icon-youjian'?'color-green':'']" v-if="con.type ==='icon-youjian'" @click.stop="isDealog('showEmailDetails',con._id,'')">{{$t('email.mailCommunication')}}</span>
                <span :class="[con.type==='icon-waihutubiao'?'color-green':'']" v-if="con.type ==='icon-waihutubiao'" @click.stop="isDealog('showCallDetails',con._id,'')">{{$t('call.callOut')}}</span>
                <span :class="[con.type==='icon-dianhuahuru'?'color-green':'']" v-if="con.type ==='icon-dianhuahuru'" @click.stop="isDealog('showCallDetails',con._id,'')">{{$t('call.callIn')}}</span>
                <span :class="[con.type==='icon-yidongduan'|| 'icon-yidongduan' || 'icon-hulianwang' || 'icon-wap' || 'icon-weixin' || 'icon-weibo' || 'icon-douyin' || 'icon-wxEnterprise-' || 'icon-liuyan'?'color-green':'']" @click.stop="isDealog('showWebChatDetails',con._id,'',con.type)">
                  <span v-if="con.type ==='icon-yidongduan'">{{$t('webchat.appCon')}}</span>
                  <span v-if="con.type ==='icon-diannao'">{{$t('webchat.websiteCon')}}</span>
                  <span v-if="con.type ==='icon-shouji'">{{$t('webchat.wapCon')}}</span>
                  <span v-if="con.type ==='icon-weixinzixun'">{{$t('webchat.weChatCon')}}</span>
                  <span v-if="con.type ==='icon-wxmini'">{{$t('webchat.weChatMini')}}</span>
                  <span v-if="con.type ==='icon-wxEnterprise-'">{{$t('report.imPlatform.enterprise')}}</span>
                  <span v-if="con.type ==='icon-weibo'">{{$t('webchat.WeiboConsultation')}}</span>
                  <span v-if="con.type ==='icon-liuyan'">{{$t('webchat.leaveMessage')}}</span>
                  <span v-if="con.type ==='icon-baiduBCP'">{{$t('webchat.baiduBCP')}}</span>
                  <span v-if="con.type ==='icon-douyin'">{{$t('webchat.platformTikTok')}}</span>
                  <span v-if="con.type ==='icon-weixinguanfangkefu'">{{$t('webchat.platformWXKF')}}</span>
                </span>
                <span v-if="con.type ==='icon-remoteassist'">{{$t('remoteControl.startModules')}}{{con.sourceType}}</span>
                  <span v-if="(con && con.labels && con.labels.length > 0) && getLabelsAuth">
                        <el-tooltip class="item" effect="dark" :content="trunLableNameByList(con.labels)" placement="right">
                          <i class="iconfont icon-biaoqian" style="position:inherit;top:0;left:0;border-bottom:0;color:#F0AD3A"></i>
                        </el-tooltip>
                  </span>
                  <span class="sessionFormBtn" v-if="con.sessionFormHistory && con.sessionFormHistory.length > 0" @click="isShowUnfold(index)">
                    {{$t('public.sessionForm')}}
                    <span :class="isFold[index] ? 'el-icon-arrow-up': 'el-icon-arrow-down'"></span>
                  </span>
                </h3>
                <p class="notes el-col-14" v-if="con.comments">
                  <!-- <el-tooltip v-if="con.comments !=='true' && NoEditNote == false" effect="dark" :content="con.comments" placement="right"> -->
                  <strong v-if="con.comments !=='true' && NoEditNote == false" :class="['iconfont', 'icon-biaoji',!con.canComments?'un-point':'']" @click.stop="editComments(con)"></strong>
                  <i v-if="con.comments !=='true' && NoEditNote == false"></i><span class="detail" v-if="con.comments !=='true' && NoEditNote == false" >
                  <span style="color: #878787;">{{con.remarkTime}} {{con.remarkUserName}} {{con.remarkUserExten}}</span>   {{con.comments}}
                </span>
                  <!-- </el-tooltip> -->
                  <strong v-if="con.comments == 'true' && NoEditNote == false" :class="['iconfont', 'icon-biaoji', 'null', !con.canComments?'un-point':'']" @click.stop="editComments(con)"></strong>
                  <strong v-if="NoEditNote == true && con.comments!=='true'" :class="['iconfont', 'icon-biaoji', NoEditNote?'un-point':'']"></strong>
                  <strong v-if="NoEditNote == true &&con.comments == 'true'&& con.callType!=='call'&&con.callType!=='note'" :class="['iconfont', 'icon-biaoji', 'null', con.callType!=='call'&&con.callType!=='note'?'un-point':'']"></strong>
                  <i v-if="NoEditNote == true && con.comments!=='true'"></i>
                  <span class="detail" v-if="con.comments !=='true' && NoEditNote == true" >
                    <span style="color: #878787;">{{con.remarkTime}} {{con.remarkUserName}} {{con.remarkUserExten}}</span>   {{con.comments}}</span>
                </p>
                <unfold :isShow="isFold[index]" :title="[]">
                  <template slot="unfoldSlot">
                    <div v-for="(formItem, i) in con.sessionFormHistory" :key="i" class="formItem">
                      <p class="fl textWidth">{{ formItem.name | filterName }}</p>
                      <el-popover
                        placement="right"
                        width="300"
                        trigger="hover">
                        <div class="formMsgLi" v-for="(data, i1) in JSON.parse(formItem.sessionFormSubmit)" :key="i1">
                          <span class="formMsgLiAttr">{{i1}}</span>:<span class="formMsgLiData" :title="data">{{data}}</span>
                        </div>
                        <p class="checkSessionForm fl" type="text" slot="reference">{{$t('webchat.view')}}</p>
                      </el-popover>
                      <p class="fr">{{formItem.time || ''}}</p>
                    </div>
                  </template>
                </unfold>
                <div style="width: 0;height: 0;clear: both;visibility: hidden;"></div>
              </li>
              <!-- <li class="treat treat__date">
                <span class="bac"></span>
                <i></i>
                <h3 class="date">
                  {{con.createTime}}
                </h3>
              </li> -->
          </template>
        </ul>
      </el-col>
    </el-row>
    <el-row v-if="isLoadMoreShow">
      <el-col :span="24" class="next-page">
        <div class="btn" @click.stop="loadMore"><span>{{$t('public.loadMore')}}</span></div>
      </el-col>
    </el-row>
    <!--<el-dialog :close-on-click-modal="false" v-model="imgShow" size="full" @close="bigImgClose" :close-on-click-modal="true" :showshow-close="false" custom-class="bigimg">-->
      <!--<div class="img-box" @click.stop="bigImgClose">-->
        <!--<img :src="imgUrl" style="max-width: 100%">-->
      <!--</div>-->
    <!--</el-dialog>-->
  </div>

</template>
<script>
  import Vue from 'vue'
  import Bussiness from '../business/index.vue'
  import CallStatus from '@/components/public-modules/cache/CallStatus.vue'
  import { isHasFunc, getCallTimeLength, getCache, innerHtmlChannelColor, getSingleOrMultiLabelNameById, getAllUseMultiCallLabel } from '@/utils/m7Utils.js'
  import emailDetails from '@/components/business-modules/email/emailDetails.vue'
  import webChatView from '@/components/business-modules/webchat/webChatView.vue'
  import AudioCommon from '@/components/public-modules/audio'
  import OldAudioCommon from '@/components/public-modules/audio/audio.vue'
  import DetailTable from '../call-detail/DetailTable.vue'
  import unfold from '@/components/ui-modules/unfold/index.vue'
//  import * as types from '@/store/mutation-types.js'

/**
 * 联系历史 里面个类型的备注
 * 联系计划：特殊： 完成后不可编辑
    通话 外呼与呼入：

    以上两种情况： 1.受权限控制  有权限则可编辑，没权限则为只读

    在线咨询与邮件：特殊： 只读

    以上：无内容则灰色图标，有内容展示内容并且绿色图标

    工单： 不展示内容与图标
*/
  export default {
    name: 'contactHistory',
    filters: {
      filterName (val) {
        return val && val !== '' ? decodeURIComponent(val) : ''
      }
    },
    data () {
      return {
        pauseAudio: 'open',
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        callData: {},
        LIMIT: 20,
        loading: true,
        count: 0,
        cons: [],
        isFold: [],
        contactHistoryInfo: {
          isdealog: false,
          labelValue: 3,
          title: '',
          _id: ''
        },
        lastEmail: {},
        chatInformation: {},
        chatWebObject: {},
        contectHistoryList: {},
        businessType: [
          { type: '', name: this.$t('public.all') },
          { type: 'note', name: this.$t('public.contactPlan') },
          { type: 'chat', name: this.$t('public.webchat') }
        ],
        time: [
          { type: 'week', name: this.$t('public.last7Days') },
          { type: 'month', name: this.$t('public.last1Month') },
          { type: 'month3', name: this.$t('public.last3Month') },
          { type: '', name: this.$t('public.all') }
        ],
        filterTime: 'week',
        filterType: '',
        listent: false,
        recordFile: '',
        callStatus: '',
        showOld: false,
        edit: false,
        editObj: null,
        _id: '',
        comments: '',
        nextPage: 1,
        isLoadMoreShow: false,
        lcafre: 'history',
        NoEditNote: false, // 备注的权限
        isListent: false, // 通话录音权限
        refreshAudio: 0,
        isOperate: false // 弹框内容被操作过，刷新列表
      }
    },
    components: {
//      Business,
      CallStatus,
      Bussiness,
      emailDetails,
      webChatView,
      AudioCommon,
      OldAudioCommon,
      unfold,
      DetailTable
    },
    deactivated () {
      this.contactHistoryInfo.isdealog = false
    },
    computed: {
//      imgShow () {
//        return this.$store.state.bigImg.imgShow
//      },
//      imgUrl () {
//        return this.$store.state.bigImg.imgUrl
//      },
      getLabelsAuth () {
        return isHasFunc('func_mark_cdr', this.$store.state.session.user)
      },
      filterTypeName () {
        let that = this
        return this.businessType.filter(val => {
          return val.type === that.filterType
        })[0].name
      },
      filterTimeName () {
        let that = this
        return this.time.filter(val => {
          return val.type === that.filterTime
        })[0].name
      },
      reload () {
        return this.refresh
      },
      getMultiCallLabel () {
        let allLabel = this.$getCache('callLabel')
        let multiObj = getAllUseMultiCallLabel(allLabel)
        return multiObj
      },
      getSingCallLabel () {
        let singleObj = this.$store.state.call.transCache.singleLabel
        return singleObj.singleLabel
      }
    },
    methods: {
      isShowUnfold (index) {
        Vue.set(this.isFold, index, !this.isFold[index])
      },
      showOldAudio (curr) {
        this.showOld = curr
      },
      open () {
        if (this.contactHistoryInfo.labelValue === 4) {
          this.pauseAudio = 'open'
        }
      },
      off () {
        if (this.contactHistoryInfo.labelValue === 1) {
          // let obj = this.$store.state.business['current'].businessAction[this.contactHistoryInfo._id] || {}
          // console.log(obj)
          if (this.isOperate) {
            this.contactHistoryInfo._id = ''
            this.nextPage = 1
            this.filterType = ''
            this.filterTime = 'week'
            this.fetchData(null)
          } else {
            this.contactHistoryInfo._id = ''
          }
        } else if (this.contactHistoryInfo.labelValue === 4) {
          let play = document.getElementById('quality-autoplay_callHistoryAudio_old')
          if (play) {
            play.pause()
          }
          this.pauseAudio = 'close'
        } else {
          this.contactHistoryInfo._id = ''
        }
      },
      businessEvent (eventData) {
        this.isOperate = true
        let data = eventData.data
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: data._id})
        }
      },
      isDealog (flag, id, title, type) {
        this.contactHistoryInfo.isdealog = true
        if (flag === 'showBussinessDetails') {
          this.$store.dispatch('getBusinessDetailById', {_id: id}).then((res) => {
            if (res) {
              this.contactHistoryInfo.title = this.$t('business.workOrderDetails')
              this.contactHistoryInfo.labelValue = 1
//          this.contactHistoryInfo.isTitle = true
              this.contactHistoryInfo._id = id
            } else {
              this.contactHistoryInfo._id = ''
              this.contactHistoryInfo.isdealog = false
            }
          })
        } else if (flag === 'showEmailDetails') {
          this.$store.dispatch('getLastEmail', {sessionId: id}).then(() => {
            this.lastEmail = this.$store.state.email.lastEmail
            this.contactHistoryInfo.title = this.$t('email.emailDetail')
            this.contactHistoryInfo.labelValue = 2
            this.contactHistoryInfo._id = id
          })
        } else if (flag === 'showCallDetails') {
          this.$store.dispatch('relocationCustomerAtTable', {_id: id, self: this}).then((resp) => {
            this.contactHistoryInfo.title = this.$t('call.modalCallInfo')
            this.contactHistoryInfo.labelValue = 4
            this.contactHistoryInfo._id = id
            this.callData = resp
          })
        } else if (flag === 'showWebChatDetails') {
          this.contactHistoryInfo._id = id
          this.contactHistoryInfo.labelValue = 3
          if (type === 'icon-liuyan') {
            this.contactHistoryInfo.title = this.$t('webchat.leaveMessage')
          } else {
            this.contactHistoryInfo.title = this.$t('webchat.sessionRecord')
          }
        }
      },
      handleCommandTime (command) {
        this.filterTime = command
        this.nextPage = 1
        this.fileContactHistory()
      },
      handleCommandType (command) {
        this.filterType = command
        this.nextPage = 1
        this.fileContactHistory()
      },
      closeModal () {
        this.pauseAudio = 'close'
        let myAudio = document.getElementById('quality-autoplay_contact_history_old')
        if (myAudio) {
          if (myAudio.currentSrc) {
            myAudio.pause()
          }
        }
      },
      openModal () {
        this.pauseAudio = 'open'
        let myAudio = document.getElementById('quality-autoplay_contact_history_old')
        if (myAudio) {
          if (myAudio.paused) {
            myAudio.currentTime = 0
            if (myAudio.currentSrc) { // url 有地址时
              myAudio.play()
            }
          }
        }
      },
      loadMore () {
        let data = {
          customer: this.cid,
          date: this.filterTime,
          type: this.filterType,
          businessType: '',
          page: ++this.nextPage,
          limit: this.LIMIT
        }
        this.fetchData(data)
      },
      fileContactHistory () {
        let data = {
          customer: this.cid,
          date: this.filterTime,
          type: this.filterType,
          businessType: '',
          page: 1,
          limit: this.LIMIT
        }
        this.fetchData(data)
      },
      fetchData (data) {
        this.isOperate = false
        if (!data) {
          data = {
            customer: this.cid,
            date: 'week',
            page: 1,
            limit: this.LIMIT
          }
          this.loading = true
        }
        return this.$store.dispatch('queryCustomerContactHistory', data).then(val => {
          console.log(val)
          this.count = val.count
          this.loading = false
          // let valArr = []
          // let indexArr = []
          let list = val.list
          let currCount = 0
          // for (let key in val.contactHistory) {
          //   valArr.push(val.contactHistory[key])
          //   indexArr.push(key)
          // }
          // let i = 0
          // let j = 0
          let cons = []
          // console.log(indexArr)
          for (let i = 0; i < list.length; i++) {
            let obj = {}
            let item = list[i]
            let type = item.type
            let sclass = item.status
            let platform = item.platform
            sclass = type === 'business' && item.dispose !== 'complete' ? 'buss' : type === 'callout' && item.status === 'dealing' ? 'callout' : type === 'callin' && (item.status === 'dealing' || item.voicemail) ? 'callin' : type === 'email' && item.status === 'still' ? 'email' : type === 'note' && item.status === 'create' ? 'note' : item.status === 'chating' ? 'webchat' : ''
            type = type === 'business' ? 'gongdan' : type === 'callout' ? 'waihutubiao' : type === 'callin' ? 'dianhuahuru' : type === 'note' ? 'lianxijihua' : type === 'email' ? 'youjian' : type === 'remoteassist' ? 'remoteassist' : type === 'leaveMsg' ? 'liuyan' : type === 'chat' && platform === 'weixin' ? 'weixinzixun' : type === 'chat' && platform === 'dy' ? 'douyin' : type === 'chat' && platform === 'wxkf' ? 'weixinguanfangkefu' : type === 'chat' && platform === 'wxmini' ? 'wxmini' : type === 'chat' && platform === 'wxwork' ? 'wxEnterprise-' : type === 'chat' && platform === 'weibo' ? 'weibo' : type === 'chat' && platform === 'pc' ? 'diannao' : type === 'chat' && platform === 'wap' ? 'shouji' : type === 'chat' && platform === 'sdk' ? 'yidongduan' : 'zaixianzixun'
            if (item.leaveMsg) {
              type = 'liuyan'
            }
            let comments = item.type === 'business' ? false : item.comments || 'true' // 工单类型不显示备注按钮
            let canComments = !(item.type === 'email' || item.type === 'chat' || (item.type === 'note' && item.status !== 'create')) // 备注：工单无；联系计划（未完成的受权限控制）、通话有权限；在线咨询、邮件只读
            item.comments = item.type === 'note' ? item.comments.replace(/\[[^\]]*\]/, '') : item.comments // 如果是联系计划，从comments里去除时间
            let callTimeLen = item.beginTime && item.endTime ? getCallTimeLength(Math.floor((item.endTime - item.beginTime) / 1000)) : 0
            const sessionFormHistory = item.sessionFormHistory || []
            obj = {
              _id: item._id,
              sort: item.agentName,
              status: item.dispose || item.disposeDisplay,
              text: item.comments,
              recordFile: item.recordFile,
              sclass: sclass, // 是灰色还是彩色，业务状态
              type: 'icon-' + type, // 业务类型icon判断
              detail: 1,
              createTime: item.createTime,
              comments: comments,
              canComments: canComments,
              callType: item.type,
              callTimeLen: callTimeLen,
              sessionFormHistory: sessionFormHistory,
              businessTypeName: item.businessTypeName,
              labels: item.labels || [],
              remarkUserName: item.remarkUserName,    //  备注 创建人 时间 相关
              remarkUserExten: item.remarkUserExten ? `[${item.remarkUserExten}]` : '',
              remarkTime: item.remarkTime ? `[${item.remarkTime}]` : '',
            }
            if (item.type === 'callin' || item.type === 'callout') {
              obj.status = item.status
            } else if (item.type === 'business') {
//                obj.status = item.businessTypeName + ' / ' + (item.dispose === 'complete' ? this.$t('public.complete') : obj.status)
              obj.status = (item.dispose === 'complete' ? this.$t('public.complete') : obj.status === 'cancel' ? this.$t('public.bussinessCancel') : obj.status)
            }
            if (item.type === 'remoteassist' && item.source === 'call') {
              obj.sourceType = this.$t('public.call')
            } else if (item.type === 'remoteassist' && item.source === 'webchat') {
              obj.sourceType = this.$t('public.webchat')
            } else if (item.type === 'remoteassist' && item.source === 'customer') {
              obj.sourceType = this.$t('public.customer')
            }
            if (item.type === 'remoteassist' && item.connLength) {
              let time = +item.connLength
              obj.connectTime = Math.ceil(time / 60)
            }
            cons.push(obj)
            this.isFold[i] = false
            // }
            // let is = indexArr[i].split('-')
            // console.log(indexArr[i])
            // console.log(is)
            // obj = {
            //   sort: `${is[1]}/`,
            //   status: is[2],
            //   date: indexArr[i],
            //   detail: 2
            // }
            // cons.push(obj)
          }
          if (this.$store.state.session.user.isAdmin || isHasFunc('func_not_edit_remark_field', this.$store.state.session.user)) {
            this.NoEditNote = true // 禁止联系历史通话备注和联系计划备注的编辑
          }
          if (this.$store.state.session.user.isAdmin || !isHasFunc('func_user_call_sheet_listen_file', this.$store.state.session.user)) {
            this.isListent = true
          }

          if (this.nextPage > 1) {
            // let lastObj = this.cons[this.cons.length - 1]
            // let hasDate = false
            // for (let i = 0; i < cons.length; i++) {
            //   if (cons[i].sort === lastObj.sort && cons[i].status === lastObj.status) {
            //     hasDate = true
            //     break
            //   }
            // }
            // if (hasDate) {
            //   this.cons.pop()
            // }
            this.cons.push(...cons)
          } else {
            this.loading = false
            this.cons = cons
          }
          // 计算总数
          this.cons.map(con => {
            if (con.detail === 1) {
              currCount++
            }
          })
          if (currCount < this.count) {
            this.isLoadMoreShow = true
          } else {
            this.isLoadMoreShow = false
          }
        })
      },
      popup (recordFile, status) {
        this.callStatus = status || ''
        if (recordFile) {
          let newRecordFile = recordFile.substring(recordFile.indexOf('monitor'))
          let FILE_NAME = recordFile.substring(0, recordFile.indexOf('monitor'))
          let fileList = newRecordFile.split('/')
          let userPbx = fileList[1]
          if (FILE_NAME.indexOf('record.7moor.com') > -1 || FILE_NAME.indexOf('m7-record.oss-cn-hangzhou') > -1 || FILE_NAME.indexOf('aliyuncs.com') > -1) {
            FILE_NAME = 'https' + FILE_NAME.substr(FILE_NAME.indexOf(':'), FILE_NAME.length)
            recordFile = FILE_NAME + newRecordFile
            this.recordFile = recordFile
            this.listent = true
          } else if (userPbx && document.location.protocol === 'https:') {
            let self = this
            if (userPbx) {
              getCache('accountPbx', userPbx, this, function (pbxObj) {
                if (pbxObj) {
                  if (pbxObj.assDomain) {
                    let assDomain = pbxObj.assDomain
                    if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                      recordFile = assDomain + newRecordFile
                    } else {
                      recordFile = assDomain + '/' + newRecordFile
                    }
                  }
                }
                self.recordFile = recordFile
                self.listent = true
              })
            } else {
              this.recordFile = recordFile
              this.listent = true
            }
          } else {
            this.recordFile = recordFile
            this.listent = true
          }
        } else {
          this.listent = true
        }
        this.refreshAudio = Math.random()
      },
      editComments (item) {
        if (item.canComments) {
          if (item.callType === 'note') {
            this.comments = item.comments.split(']')[1]
          } else {
            this.comments = item.comments === 'true' ? '' : item.comments
          }
          this.edit = true
          this.editObj = item
        }
      },
      submitEdit () {
        console.log(this.editObj)
        if (this.editObj && this.editObj.callType === 'note') {
          let data = {
            _id: this.editObj._id,
            remark: this.comments,
            notifyTime: this.editObj.comments.split(']')[0].replace('[', ''),
            accountId: this.$store.state.session.user.account,
            userId: this.$store.state.session.user._id,
            customerId: this.cid
          }
          if (this.comments.length > 140) {
            this.$message.error(this.$t('public.notExceed'))
            return
          }
          if (this.comments.length === 0) {
            this.$message.error(this.$t('public.noEmpty'))
            return
          }
          this.$store.dispatch('updateCustomerContactPlan', data).then(resp => {
            updateRemark(this.cons, this.editObj._id, this.comments, data.notifyTime)
            this.edit = false
            this.editObj = null
            this.$message.success(this.$t('public.modifyNoteSuccess'))
          })
        } else if (this.editObj && (this.editObj.callType === 'callin' || this.editObj.callType === 'callout')) {
          let data = {
            CALL_SHEET_ID: this.editObj._id,
            memo: this.comments
          }
          let routeArry = this.$route.path.split('/')
          let tabType = routeArry[3]
          this.$store.dispatch('updateCustomerCdrRemark', data).then(resp => {
            updateRemark(this.cons, this.editObj._id, this.comments)
            if (tabType && tabType.indexOf('cdr') >= 0) {
              this.$store.commit('call/COMMENTS', {id: this.editObj._id, memo: this.comments, tabType: tabType})
              this.$store.commit('call/COMMENTS', {id: this.editObj._id, memo: this.comments, tabType: 'cdr_call'})
              this.$store.commit('call/COMMENTS', {id: this.editObj._id, memo: this.comments, tabType: 'cdr_outbound'})
            }
            this.edit = false
            this.editObj = null
            this.$message.success(this.$t('public.modifyNoteSuccess'))
          })
        } else if (this.editObj && this.editObj.callType === 'remoteassist') {
          let data = {
            _id: this.editObj._id,
            memo: this.comments
          }
          if (this.comments.length > 140) {
            this.$message.error(this.$t('public.notExceed'))
            return
          }
          if (this.comments.length === 0) {
            this.$message.error(this.$t('public.noEmpty'))
            return
          }
          this.$store.dispatch('updateCustomerRemoteAssistRemark', data).then(resp => {
            if (resp.success) {
              updateRemark(this.cons, this.editObj._id, this.comments, data.notifyTime)
              this.edit = false
              this.editObj = null
              this.$message.success(this.$t('public.modifyNoteSuccess'))
            }
          })
        }
      },
      trunLableNameById (item) { // 通话标签id来匹配标签名字
        let labelType = item.indexOf('@') !== -1 ? 'multi' : 'single'
        if (!item) {
          return ''
        }
        if (labelType === 'single') {
           const singleName = getSingleOrMultiLabelNameById(this.getSingCallLabel, item) || ''
           return singleName
        } else {
            let usedLabel = []
            if (item.indexOf('@') !== -1) { // 判断是不是多级
              usedLabel = item.split('@') // @1@2@3拆分为数组
              usedLabel.pop()
            }
            let labelName = ''
            const allKeyLabels = this.$store.state.allKeyLabels || {}
            for (let j = 0; j < usedLabel.length; j++) {
              const labelStr = allKeyLabels !== {} ? allKeyLabels[usedLabel[j]] : ''
              if (labelStr) {
                labelName += labelStr + '>'
              }
            }
            labelName = labelName.substring(0, labelName.length - 1)
            this.hasSingle = false
            return labelName
        }
      },
      trunLableNameByList (labels) {
        let labelStr = ''
        if (typeof labels === 'string') {
          labels = JSON.parse(labels)
        }
        if (labels && labels.length > 0) {
          labels.forEach((item, index) => {
            labelStr += this.trunLableNameById(item)
            if (index !== (labels.length -1)) {
              labelStr += ' / '
            }
          })
        }
        return labelStr
      }
    },
    props: {
      cid: String,
      refresh: {
        type: String,
        default: null
      },
      type: String,
      callScreen: Boolean
    },
    watch: {
      refresh (cur, old) {
        if (cur === 'history') {
          this.filterTime = 'week'
          this.filterType = ''
          this.fetchData(null)
          this.nextPage = 1
        }
      },
      cid (cur, old) {
        if (cur !== '' && this.type === 'webchatNewHistory') {
          // 在线咨询右侧联系历史刷新
          this.filterTime = 'week'
          this.filterType = ''
          this.fetchData(null)
          this.nextPage = 1
        }
      },
      $route (to, from) {
        if (this.refresh === 'history' || to.path.split('/')[3] === 'webchat_todo') {
          this.fetchData(null)
          this.nextPage = 1
        }
      },
      cons (cur, old) {
        if (old.length > 10) {
          this.$nextTick(function () {
            // document.getElementById('isSrcollBottom').children[0].children[1].scrollTop = document.getElementById('isSrcollBottom').children[0].children[1].scrollHeight
          })
        }
      }
    },
    created () {
      if (this.refresh === 'history' && this.cid) {
        this.fetchData(null)
      }
    },
    beforeMount () {
      let self = this
      if (this.flag !== 'ecommerce') {
        this.businessType = [
          { type: '', name: this.$t('public.all') },
          { type: 'business', name: this.$t('public.business') },
          { type: 'note', name: this.$t('public.contactPlan') },
          { type: 'chat', name: this.$t('public.webchat') },
          { type: 'email', name: this.$t('public.mail') },
          { type: 'callin', name: this.$t('public.callIn') },
          { type: 'callout', name: this.$t('public.callOut') },
          { type: 'remoteassist', name: this.$t('remoteControl.remoteControl') }
        ]
      }
      this.$store.dispatch('getCache', {type: 'channelGlobalSet'}).then((channelGlobalSet) => {
        innerHtmlChannelColor(self)
      })
    }
  }
  function updateRemark (arr, _id, remark, notifyTime) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i]._id === _id) {
        arr[i].text = remark
        if (arr[i].callType === 'note') {
          arr[i].comments = `[${notifyTime}]${remark}`
        } else {
          arr[i].comments = remark || 'true'
        }
      }
    }
  }
</script>
<style lang="stylus" scoped>
@import '../../../../assets/common.styl'
.color-green
  color $c-main
  cursor pointer
.next-page
  margin-bottom 20px
  .np-btn
    width 380px
    background $c-main
    border 1px solid $c-main
.p-filter
  margin-top -10px
  padding 0 12px 10px
  &:before
    content ''
    height 1px
    width calc(100% + 40px)
    position absolute
    top 29px
    left -20px
    border-bottom 1px solid $c-border1
.right
  text-align right
.icon-biaoji
  margin-top 7px
  font-size 14px
  color $c-main
  cursor pointer
.null
  color $cf-gray5
.clock
  display inline-block
  position  relative
  top  1px
  width 14px
  height 16px
  line-height 16px
  margin-right 8px
  .iconfont
    font-size 16px
.el-dropdown-link
  color $c-main
  cursor pointer
.el-button
  /*padding  0*/
  span
    display inline-block
    width  14px
    height 14px
    background $c-prompt
.til
  color $cf-gray6
  font-size 12px
  .icon-zongshichang
    color $cf-gray5
.line
  padding-top  30px
.border
  padding-left 10em
  .treat
    position relative
    padding 0 0 0 25px
    margin-left 56px
    border-left 1px solid $c-border1
    font-size 0
    min-height 54px
    i
      position absolute
      display inline-block
      width 26px
      border-bottom 1px solid $c-his-border
      top 19px
      left 10px
    img
      position relative
      top -4px
      margin 0 4px
    /*&:last-child
      .bac
        height 50px
        background $cf-white
    .bac
      height 12px
      width 54px
      background $cf-white
      padding 1px 0
      position absolute
      left -48px
      top 10px
      &:before
        content ""
        width 12px
        height 12px
        display inline-block
        float right
        border-radius 6px
        background-color $cf-level2*/
    .timer
      width 10em
      position absolute
      left calc(-10em - 45px)
      line-height 34px
      font-size 12px
      color $cf-gray4
      text-align right
      &:after
        content ''
        position absolute
        margin-left 5px
        width 15px
        height 0
        top 17px
        border-bottom 1px solid #c4c4c4
    .ico
      width: 32px
      height: 32px
      line-height 32px
      position: absolute
      z-index 10
      left: -17px
      /*top: 4px*/
      border-radius 50%
      border 1px solid $cf-level2
      color $cf-level2
      text-align center
      background $cf-white
      .iconfont
        font-size 18px
        font-weight normal
      &:first-child
        top 0
    .note
      color #f3a720
      border-color #f3a720
    .callin
      color #44b7b2
      border-color #44b7b2
    .callout
      color #44b7b2
      border-color #44b7b2
    .webchat, .hulianwang, .yidongduan, .weixinzixun
      color #44b7b2
      border-color #44b7b2
    .webchat .icon-diannao
      color #2496d0
      border-color #2496d0
    .webchat .icon-yidongduan
      color #5cc1f6
      border-color #5cc1f6
    .webchat .icon-weixinzixun
      color #85bf52
      border-color #85bf52
    .webchat .icon-wxmini
      color #85bf52
      border-color #85bf52
    .webchat .icon-douyin
      color #85bf52
      border-color #85bf52
    .webchat .icon-weixinguanfangkefu
      color #85bf52
      border-color #85bf52
    .webchat .icon-weibo
      color #fa7d3c
      border-color #fa7d3c
    .webchat .icon-shouji
      color #29ba9c
      border-color #29ba9c
    .webchat .icon-wxEnterprise-
      color #459ae9
      border-color #459ae9
    .email
      color $c-busy
      border-color $c-busy
    .buss
      color #e3746b
      border-color #e3746b
    .buss .icon-gongdan
      color #3b5998
      border-color #3b5998
    .note .icon-lianxijihua
      color #f5a623
      border-color #f5a623
    .callout .icon-waihutubiao
      color #2bb24c
      border-color #2bb24c
    .callin .icon-dianhuahuru
      color #2bb24c
      border-color #2bb24c
    .icon-yuanchengkongzhi
      color #29ba9c
      border-color #29ba9c
    .icon-remoteassist
      color #29ba9c
      border-color #29ba9c
    .geton
      border-color #f6b549
      .iconfont
        color #f6b549
    .finish
      border-color #bbb
      .iconfont
        color #bbb
    .by
      border-color #e3746f
      .iconfont
        color #e3746f
    .goline
      border-color #b3b3b3
      .iconfont
        color #b3b3b3
    .get_on
      border-color #45b6b0
      top 22px
      .iconfont
        color #45b6b0
    .last
      background-color $cf-white
      background-position right top
      height 22px
      top 20px
    p
      font-size 12px
      color $cf-gray4
    .notes
      display inline-block
      display flex
      margin-top -1px
      /*align-items center*/
      /*width calc(100% - 400px)*/
      .write
        width 14px
        height 14px
        position relative
        top 2px
        cursor pointer
      .memo
        padding 3px 10px
        margin-left 8px
        color $cf-white
        background #65bef2
        border-radius 2px
        position relative
        top 2px
        width calc(100% - 50px)
        &:before
          content ''
          width 0px
          height 0px
          border 6px solid transparent
          border-right-color #65bef2
          position absolute
          left -12px
          top 5px
      .detail
        color $cf-gray4
        height 20px
        position relative
        text-overflow:ellipsis
        overflow:hidden
        white-space: nowrap
        width calc(100% - 45px)
        padding 5px 10px
        border-radius 4px
        line-height 20px
        background #f2f2f2
        margin-bottom 5px
      .detail:hover
        height auto
        white-space normal
      i
        position static
        margin-left 4px
        margin-top 10px
        width 0
        height 0
        border 4px solid #f2f2f2
        border-color transparent #f2f2f2 transparent transparent
    .time
      bottom: 2px
      border-radius: 4px
      padding: 0 4px
      font-size: 12px
      margin-left: 5px
      width 80px
      cursor: pointer
      box-sizing border-box
      padding-left 6px
      .play
        width: 12px
        height:12px
        line-height 12px
        border 1px solid $c-main
        border-radius 50%
        display inline-block
        .pla
          display inline-block
          width 0
          height 0
          border 4px solid $c-main
          border-color:transparent transparent transparent $c-main;
          /*margin-left 5px*/
          /*margin-top 3px*/
          position relative
          top 0px
          left 5px
    h3
      display: inline-block
      padding: 0
      /*width: 340px*/
      font-size 14px
      color $cf-gray2
      text-overflow:ellipsis
      overflow:hidden
      white-space: nowrap
      span
        position: relative
        font-weight: normal
      .succes
        margin-left:18px
        width: 20px
        height: 20px
        top: 2px
        .iconfont
          font-size 20px
          color #5cbfba
    /*.date
      color $cf-white
      height 30px
      width 90px
      line-height 30px
      background $c-sub6
      text-align center
      border-radius 8px
      span
        font-size 18px*/
    li
      &:first-child
        padding-top 0
        /*&:before
          content ""
          width 1px
          height 70px
          display inline-block
          position absolute
          top 35px
          left 0
          background-color $c-his-border*/
    &:last-child
      margin-bottom: 20px
      height: 20px
      border 0
  .treat .call-h3 span
    display inline
      h3
        display: inline-block
        padding: 0
        /*width: 340px*/
        font-size 14px
        color $cf-gray2
        /*text-overflow:ellipsis
        overflow:hidden
        white-space: nowrap*/
        span
          display: inline-block
          position: relative
          font-weight: normal
        .time
          bottom 2px
          border-radius 4px
          padding 0 4px
          background $c-sub
          font-size 12px
          color $cf-white
          margin-left 26px
          width 80px
          cursor pointer
          box-sizing border-box
          padding-left 6px
          .play
            width 12px
            height 12px
            line-height 12px
            border 1px solid $cf-white
            border-radius 50%
            .pla
              display inline-block
              width 0
              height 0
              border 4px solid $cf-white
              border-color:transparent transparent transparent $cf-white;
              /*margin-left 5px*/
              /*margin-top 3px*/
              position relative
              top 0px
              left 5px
        .succes
          margin-left:18px
          width: 20px
          height: 20px
          top: 2px
          .iconfont
            font-size 20px
            color #5cbfba
      /*.date
        color $cf-white
        height 24px
        width 70px
        line-height 24px
        background $c-sub
        text-align center
        border-radius 8px
        margin-top 12px
        padding 0
        color $cf-white
        margin-top -2px
        span
          font-size 18px*/
    li
      &:first-child
        border-left 0
        &:before
          content ""
          width 1px
          height 60px
          display inline-block
          position absolute
          top 35px
          left 0
          background-color $c-his-border
      &:last-child
        margin-bottom: 60px
        height: 20px
    .treat .call-h3 span
      display inline
.btn
  cursor pointer
  color $c-main
  padding-left 160px
  .icon-shuaxin
    display inline-block
    span
      font-size 12px
      float right
      padding-left 5px
.next-page
  padding-bottom 20px
.zhezhao
  position fixed
  top 0px
  left 0
  right 0
  bottom 0
  background $cf-gray0
  opacity .5
  z-index 12
.hide-zhezhao
  display none
.show-zhezhao
  display block
.line
  .treat__date
    min-height 33px
.un-point
  cursor not-allowed
.sessionFormBtn
  color #459ae9
  margin-left 10px
  cursor pointer
.checkSessionForm
  font-size 12px
  padding-left: 10px;
  cursor: pointer;
  color: #459AE9;
.formItem
  clear: both;
  overflow: hidden;  
</style>
